package main

import (
	"bufio"
	"fmt"
	"github.com/tebeka/selenium"
	"os"
	"os/signal"
	"strconv"
	"strings"
	"time"
)

const (
	seleniumPath = "D:\\chromedriver.exe"
	port         = 9515
)

func main() {
	c := make(chan os.Signal)
	signal.Notify(c)
	opts := []selenium.ServiceOption{}
	service, err := selenium.NewChromeDriverService(seleniumPath, port, opts...)
	if err != nil {
		fmt.Println("start a chromedriver service falid", err.Error())
		return
	}
	defer service.Stop()
	caps := selenium.Capabilities{"browserName": "chrome"}
	path := "D:/video.txt"
	videoSlice, err := ReadFile(path)
	if err != nil {
		fmt.Println("读取文件错", err.Error())
		return
	}
	for _, domain := range videoSlice {
		go func(domain string) {
			temp := strings.Split(domain, ",")
			url := temp[0]
			second, _ := strconv.ParseUint(temp[1], 10, 64)
			//调起chrome浏览器
			w_b1, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", port))
			if err != nil {
				fmt.Println("connect to the webDriver faild", err.Error())
				return
			}
			//关闭一个webDriver会对应关闭一个chrome窗口
			//但是不会导致seleniumServer关闭
			defer w_b1.Quit()
			err = w_b1.Get(url)
			if err != nil {
				fmt.Println("get page faild", err.Error())
				return
			}
			for {
				time.Sleep(time.Duration(second) * time.Second)
				w_b1.Refresh()
			}
		}(domain)
		time.Sleep(10 * time.Second)
	}
	<-c
}

func ReadFile(path string) ([]string, error) {
	fileHanle, err := os.OpenFile(path, os.O_RDONLY, 0666)
	if err != nil {
		return nil, err
	}
	defer fileHanle.Close()
	scanner := bufio.NewScanner(fileHanle)
	var results []string
	// 按行处理txt
	for scanner.Scan() {
		lineTxt := strings.TrimSpace(scanner.Text())
		if len(lineTxt) == 0 {
			continue
		}
		results = append(results, lineTxt)
	}
	fmt.Printf("read result:%v\n", results)
	return results, nil
}
